package com.stooscloud.provider.impl.factory;

import com.stooscloud.DESUtil;
import com.stooscloud.JacksonUtil;
import com.stooscloud.base.exception.BusinessException;
import com.stooscloud.core.redis.IdGeneratorUtil;
import com.stooscloud.provider.impl.doman.Idcheck;
import com.stooscloud.provider.inter.factory.BuilderObjFactory;
import com.stooscloud.provider.util.DTOBuilder;
import config.properties.WsProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

@Component
@Slf4j
public class IdCheckBuilderFactory implements BuilderObjFactory<Idcheck> {
    @Resource
    WsProperties wsProperties;
    @Value("${spring.redis.host}")
    private String host;
    @Value("${spring.redis.port}")
    private int port;
    @Value("${spring.redis.timeout}")
    private int timeout;
    @Value("${spring.redis.password}")
    private String password;

    @Override
    public Idcheck builderObj(Object obj) {
        Idcheck idcheck = null;
        try {
            if (obj instanceof HttpServletRequest){
                HttpServletRequest request = (HttpServletRequest)obj;
                idcheck = (Idcheck) DTOBuilder.getDTO(request,Idcheck.class);
            }else if(obj instanceof String){
                String json = (String)obj;
                idcheck = JacksonUtil.parseJson(json,Idcheck.class);
            }else{
                log.error("没有该类型的报文,不能解析报文");
                throw new BusinessException(1007,"没有该类型的报文");
            }
        }catch (Exception e){
            log.error("映射obj到实体类失败,请检查报文");
            throw new BusinessException(1008,"报文转换失败");
        }

        log.info("解析报文成功");
        decrypt(idcheck);
        log.info("解密报文信息成功");
        idcheck.setAppid(wsProperties.getIdchk().getAppid());
        idcheck.setTrans_id(getId());
        return idcheck;
    }

    /**
     * 解密字段信息
     * @param idcheck
     */
    private void decrypt(Idcheck idcheck){
        try {
            idcheck.setIdCode(DESUtil.getDecrypt(idcheck.getIdCode(),wsProperties.getDes().getPassword()));
            idcheck.setName(DESUtil.getDecrypt(idcheck.getName(),wsProperties.getDes().getPassword()));
        } catch (Exception e) {
            log.error("解密信息失败!",e);
            throw new BusinessException(1006,"解密信息失败!",e);
        }
    }

    /**
     * 获取唯一ID
     * @return
     */
    private long getId(){
        log.info("开始生成系统唯一编号");
        return IdGeneratorUtil.getId(host,port,timeout,password,
                wsProperties.getRedis().getLuaSha(),wsProperties.getRedis().getTab(),System.currentTimeMillis());
    }
}
